#!/usr/bin/env python

import sys
from optparse import OptionParser
from grammy.main import check

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-f', '--file',
                      dest='filename',
                      metavar='FILE')
    parser.add_option('-o', '--out',
                      dest='out',
                      metavar='OUT_FILE')
    (options, args) = parser.parse_args()
    fp = getattr(options, 'filename')
    out = getattr(options, 'out')
    if fp:
        result = check(fp)
        if not result:
            print 'Compilation Failed'
            sys.exit(1)
        compiled = '\n'.join(result)
        if not out:
            print compiled
            sys.exit(0)
        else:
            out_file = open(out, 'wb')
            out_file.write(compiled)
            out_file.close()
            sys.exit(0)
    else:
        print parser.format_help()


